package com.tarry.thread;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.Queue;

/**
 * 生产者消费者模式中的生产者
 */
@Slf4j
@AllArgsConstructor
public class Producer implements Runnable{

    private Queue<String> bags;

    private int maxSize;

    @Override
    public void run() {
        int i = 0;
        while (true) {
            i ++ ;
            // 抢占锁
            synchronized (this.bags) {
                if (this.bags.size() == this.maxSize) {
                    log.warn("the bags is full ~~~");
                    // bags满了，阻塞当前线程，释放当前抢占的锁
                    try {
                        this.bags.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.info("producer product bag :" + i);
                this.bags.add("bag" + i);
                // 通知消费者，已生产bag 可以进行消费
                this.bags.notify();
            }
        }
    }
}
